package logger

import (
	"encoding/json"
	"strconv"
	"oxy_server/model"
	"oxy_server/module/log"
	"oxy_server/until"

	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"
)

type (
	Logger struct {
		ID         bson.ObjectId `json:"_id" bson:"_id"`
		User       string        `json:"user" bson:"user"`
		Role       string        `json:"role" bson:"role"`
		RemoteIP   string        `json:"remoteip" bson:"remoteip"`
		Time       string        `json:"time" bson:"time"`
		Method     string        `json:"method" bson:"method"`
		URI        string        `json:"uri" bson:"uri"`
		Status     string        `json:"status" bson:"status"`
		Body       string        `json:"body" bson:"body"`
		Beforebody string        `json:"beforebody" bson:"beforebody"`
	}
)
type OXYLog struct{}

func NewOXYLog() *OXYLog {
	Data := &OXYLog{}
	return Data
}

func (v1 *OXYLog) GetListHandler(c echo.Context) error {
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "log"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, count, err := model.DB().QuerySort(M, currentpage, perpage, "-time")
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []Logger{}
	query.All(&ps)
	str, err := json.Marshal(ps)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  string(str),
		"count": count,
	})

	return nil
}

func (v1 *OXYLog) DelHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("DelAccountingHandler", id)
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "log"
	err := model.DB().Remove(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		log.Error("删除出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
